package com.jtny.nytb.equipment.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.jtny.component.core.util.PageUtils;
import com.jtny.component.core.util.QueryWrapperUtils;
import com.jtny.component.entity.PageData;
import com.jtny.component.exception.ServiceException;
import com.jtny.component.util.Assert;
import com.jtny.component.util.BeanUtils;
import com.jtny.nytb.equipment.dao.dataparam.*;
import com.jtny.nytb.equipment.dao.model.ModelDAO;
import com.jtny.nytb.equipment.dao.rule.CodeRuleDictDAO;
import com.jtny.nytb.equipment.domain.dataparam.*;
import com.jtny.nytb.equipment.domain.model.ModelDO;
import com.jtny.nytb.equipment.domain.rule.CodeRuleDictDO;
import com.jtny.nytb.equipment.dto.dataparam.AlarmTempDTO;
import com.jtny.nytb.equipment.dto.dataparam.AlgorithmTempDTO;
import com.jtny.nytb.equipment.dto.dataparam.DataParamTempDTO;
import com.jtny.nytb.equipment.enums.CodeRuleTypeEnum;
import com.jtny.nytb.equipment.pool.TenantDataCalThreadPool;
import com.jtny.nytb.equipment.service.DataParamTempService;
import com.jtny.nytb.equipment.utils.ThreadLocalUtils;
import com.jtny.nytb.equipment.vo.dataparam.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.ServerException;
import java.util.*;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 设备参量临时数据ServiceImpl
 *
 * @author 智慧能源中心 - 伍天宇
 * @package com.jtny.energymonitor.equipment.service.impl
 * @fileName DataParamTempServiceImpl.java
 * @createTime 2023年09月19日 14:54
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Service
@AllArgsConstructor
public class DataParamTempServiceImpl implements DataParamTempService {
    @Autowired
    private ModelDAO modelDAO;

    @Autowired
    private DataParamTempDAO dataParamTempDAO;

    @Autowired
    private AlarmTempDAO alarmTempDAO;

    @Autowired
    private AlgorithmTempDAO algorithmTempDAO;

    @Autowired
    private LabelTempDAO labelTempDAO;

    @Autowired
    private ParamTempDAO paramTempDAO;

    @Autowired
    private CodeRuleDictDAO codeRuleDictDAO;

    /**
     * 分页查询
     *
     * @param dataParamTempPageQueryParamVO 设备数据参数临时页面查询参数 DTO
     * @return {@link PageData}<{@link DataParamPageVO}>
     */
    @Override
    public PageData<DataParamPageVO> page(DataParamTempPageQueryParamVO dataParamTempPageQueryParamVO) {
        // 封装查询条件QueryWrapper对象
        QueryWrapper<DataParamTempDO> queryWrapper = buildQueryWrapper(dataParamTempPageQueryParamVO);
        if (ObjectUtil.isNull(queryWrapper)) {
            return new PageData<>();
        }
        // 分页查询用户信息
        Page<DataParamTempDO> page = Page.of(dataParamTempPageQueryParamVO.getPageNo(), dataParamTempPageQueryParamVO.getPageSize());
        PageData<DataParamTempDO> pageDataForDO = PageUtils.getPageData(dataParamTempDAO.selectPage(page, queryWrapper), dataParamTempPageQueryParamVO);
        PageData<DataParamPageVO> result = pageDataForDO.transformData(DataParamPageVO.class);
        setAlgorithm(result.getData());
        return result;
    }

    private QueryWrapper<DataParamTempDO> buildQueryWrapper(DataParamTempPageQueryParamVO dataParamTempPageQueryParamDTO) {
        QueryWrapper<DataParamTempDO> queryWrapper = QueryWrapperUtils.getQueryWrapper(dataParamTempPageQueryParamDTO);

        if (ObjectUtil.isNotNull(dataParamTempPageQueryParamDTO.getAlgorithmId())) {
            List<TempAlgorithmRelationDO> temp = algorithmTempDAO.selectList(new LambdaQueryWrapper<TempAlgorithmRelationDO>()
                    .eq(TempAlgorithmRelationDO::getAlgorithmId, dataParamTempPageQueryParamDTO.getAlgorithmId()));
            if (CollUtil.isEmpty(temp)) {
                return null;
            }
            List<Long> dataParamIds = temp.stream()
                    .map(TempAlgorithmRelationDO::getDataParamId)
                    .distinct().collect(Collectors.toList());
            queryWrapper.in("id", dataParamIds);
        }

        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }


    private void setAlgorithm(Collection<DataParamPageVO> data) {
        if (CollUtil.isEmpty(data)) {
            return;
        }
        List<Long> dataParamIds = data.stream().map(DataParamPageVO::getId).collect(Collectors.toList());
        List<TempAlgorithmRelationDO> tempAlgorithmRelationList = algorithmTempDAO.selectList(new LambdaQueryWrapper<TempAlgorithmRelationDO>()
                .in(TempAlgorithmRelationDO::getDataParamId, dataParamIds));

        if (CollUtil.isEmpty(tempAlgorithmRelationList)) {
            return;
        }
        Map<Long, String> mapAlgorithmRelation = tempAlgorithmRelationList.stream()
                .collect(Collectors.toMap(TempAlgorithmRelationDO::getDataParamId, TempAlgorithmRelationDO::getAlgorithmName));
        data.forEach(dto -> dto.setAlgorithmName(mapAlgorithmRelation.getOrDefault(dto.getId(), "")));
    }

    /**
     * 保存 设备参量临时数据
     *
     * @param dataParamTempVO Data param temp dto
     * @return {@link Boolean}
     */
    @Override
    @Transactional(rollbackFor = ServerException.class)
    public Boolean save(DataParamTempVO dataParamTempVO) {
        DataParamTempDO paramTempDO = BeanUtils.copyToObject(dataParamTempVO, DataParamTempDO.class);
        boolean result = SqlHelper.retBool(dataParamTempDAO.insert(paramTempDO));
        if (result) {
            Long dataParamTempId = paramTempDO.getId();
            cleanAllId(dataParamTempVO);
            // 保存 公式对象
            toSaveAlgorithm(dataParamTempVO.getAlgorithm(), dataParamTempId);
            // 保存 报警列表
            toSaveAlarmList(dataParamTempVO.getAlarmList(), dataParamTempId);
            // 保存 标签列表
            toSaveLabelList(dataParamTempVO.getLabelList(), dataParamTempId);
        }
        return result;
    }

    /**
     * 保存设备参量临时数据
     *
     * @param dataParamTempDTOList 设备参量临时数据
     */
    @Override
    @Transactional(rollbackFor = ServerException.class)
    public void saveBatchDataParamTemp(List<DataParamTempVO> dataParamTempDTOList) {
        if (CollUtil.isEmpty(dataParamTempDTOList)) {
            return;
        }
        dataParamTempDTOList.forEach(this::save);
    }

    public void saveBatch(List<DataParamTempVO> dataParamTempVOList, Long relationId, Integer relationType) {
        if (CollUtil.isEmpty(dataParamTempVOList)) {
            return;
        }
        dataParamTempVOList.forEach(dataParamTempVO -> {
            dataParamTempVO.setRelationId(relationId);
            dataParamTempVO.setRelationType(relationType);
            save(dataParamTempVO);
        });
    }

    /**
     * 更新 设备参量临时数据
     *
     * @param dataParamTempVO Data param temp dto
     * @return {@link Boolean}
     */
    @Override
    @Transactional(rollbackFor = ServerException.class)
    public Boolean update(DataParamTempVO dataParamTempVO) {
        DataParamTempDO paramTempDO = BeanUtils.copyToObject(dataParamTempVO, DataParamTempDO.class);
        boolean result = SqlHelper.retBool(dataParamTempDAO.updateById(paramTempDO));
        if (result) {
            Long dataParamTempId = paramTempDO.getId();
            cleanAllId(dataParamTempVO);
            // 保存 公式对象
            toSaveAlgorithm(dataParamTempVO.getAlgorithm(), dataParamTempId);
            // 保存 报警列表
            toSaveAlarmList(dataParamTempVO.getAlarmList(), dataParamTempId);
            // 保存 标签列表
            toSaveLabelList(dataParamTempVO.getLabelList(), dataParamTempId);
        }
        return result;
    }

    /**
     * 根据id查询 设备参量临时数据
     *
     * @param id 设备参量临时数据id
     * @return {@link DataParamTempVO}
     */
    @Override
    public DataParamTempVO getById(Long id) {
        DataParamTempDO paramTempDO = dataParamTempDAO.selectById(id);
        Assert.notNull(paramTempDO, "设备参量临时数据不存在");
        return buildDataParamTempVO(paramTempDO);
    }

    /**
     * 根据name查询 设备参量临时数据
     *
     * @param name 设备参量临时数据name
     * @return {@link DataParamTempVO}
     */
    @Override
    public DataParamTempVO getDataParamTempByName(String name) {
        DataParamTempDO paramTempDO = dataParamTempDAO.selectOne(new LambdaQueryWrapper<DataParamTempDO>()
                .eq(DataParamTempDO::getName, name)
                .last("limit 1"));
        if (ObjectUtil.isNotNull(paramTempDO)) {
            // 目前只需要返回基础字段即可
            return BeanUtils.copyToObject(paramTempDO, DataParamTempVO.class);
        }
        return null;
    }

    private TenantDataCalThreadPool tenantDataCalThreadPool;
    @Override
    @Async
    public void importDataParamDTO(String tenantId, List<DataParamTempDTO> dataParamDTOList) {
        if (dataParamDTOList.isEmpty()) {
            return;
        }
//        List<List<DataParamTempDTO>> split = CollUtil.split(dataParamDTOList, 100);
        List<CompletableFuture> completableFutures = new ArrayList<>();
//        split.forEach(list ->
        completableFutures.add(CompletableFuture.runAsync(() -> {
            try {
                ThreadLocalUtils.setTenantCode(tenantId);
                saveBatchDataParamTemp(BeanUtils.copyToList(dataParamDTOList, DataParamTempVO.class));
            } finally {
                ThreadLocalUtils.localTenantCode.remove();
            }
        }, tenantDataCalThreadPool));
//        );
//        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
    }


    public Boolean save(DataParamTempDTO dataParamTempDTO) throws ServiceException {
        DataParamTempDO paramTempDO = BeanUtils.copyToObject(dataParamTempDTO, DataParamTempDO.class);
        boolean result = SqlHelper.retBool(dataParamTempDAO.insert(paramTempDO));
        if (result) {
            Long dataParamTempId = paramTempDO.getId();
            cleanAllId(BeanUtils.copyToObject(dataParamTempDTO,DataParamTempVO.class));
            // 保存 公式对象
            toSaveAlgorithm(BeanUtils.copyToObject(dataParamTempDTO.getAlgorithm(), AlgorithmVO.class), dataParamTempId);
            // 保存 报警列表
            toSaveAlarmList(BeanUtils.copyToList(dataParamTempDTO.getAlarmList(),AlarmVO.class), dataParamTempId);
            // 保存 标签列表
            toSaveLabelList(BeanUtils.copyToList(dataParamTempDTO.getLabelList(),LabelVO.class), dataParamTempId);
        }
        return result;
    }



    /**
     * 删除 设备参量临时数据
     *
     * @param id 设备参量临时数据id
     * @return {@link Boolean}
     */
    @Override
    @Transactional(rollbackFor = ServerException.class)
    public Boolean delete(Long id) {
        // 保存 公式对象
        toSaveAlgorithm(null, id);
        // 保存 报警列表
        toSaveAlarmList(null, id);
        // 保存 标签列表
        toSaveLabelList(null, id);

        return SqlHelper.retBool(dataParamTempDAO.deleteById(id));
    }


    public Boolean deleteAll(List<Long> ids) {
        // 保存 公式对象
        algorithmTempDAO.delete(new LambdaQueryWrapper<TempAlgorithmRelationDO>().in(TempAlgorithmRelationDO::getDataParamId, ids));
        // 保存 报警列表
        alarmTempDAO.delete(new LambdaQueryWrapper<AlarmTempDO>().in(AlarmTempDO::getDataParamId, ids));
        // 保存 标签列表
        labelTempDAO.delete(new LambdaQueryWrapper<LabelTempDO>().in(LabelTempDO::getDataParamId, ids));
        return SqlHelper.retBool(dataParamTempDAO.deleteBatchIds(ids));
    }


    /**
     * 按规则字典 ID 移动数据参量
     *
     * @param ruleDictIds 规则字典 ID
     * @param modelId     设备模型 ID
     */
    @Override
    public void moveDataParamTempByRuleDictIds(Long modelId, List<String> ruleDictIds) {
        ModelDO modelDO = modelDAO.selectById(modelId);
        // 所有数据的详情
        List<DataParamTempVO> dataParamTempVOList =
                listByRuleDictIds(CodeRuleTypeEnum.getEnum(modelDO.getIsMeasuringPointDeviceModel()).getType(), ruleDictIds);
        // 复制一份数据
        dataParamTempVOList.forEach(dataParam -> {
            dataParam.setId(null);
            dataParam.setRelationType(2);
            dataParam.setRelationId(modelId);
            dataParam.setIsCopyFromRule(Boolean.TRUE);
            save(dataParam);
        });
    }

    /**
     * 按规则字典 ID 移动数据参量
     *
     * @param modelId 型号编号
     */
    @Override
    public void backDataParamTemp(Long modelId) {
        List<DataParamTempDO> dataParamTempDOS = dataParamTempDAO.selectList(new LambdaQueryWrapper<DataParamTempDO>()
                .eq(DataParamTempDO::getIsCopyFromRule, Boolean.TRUE)
                .eq(DataParamTempDO::getRelationType, 2)
                .eq(DataParamTempDO::getRelationId, modelId));
        if (CollUtil.isNotEmpty(dataParamTempDOS)) {
            dataParamTempDOS.stream().map(DataParamTempDO::getId).forEach(this::delete);
        }
    }

    /**
     * 获取设备参量列表 按规则字典 ID
     *
     * @param ruleDictIds 规则字典 IDS
     * @return {@link List}<{@link DataParamTempVO}>
     */
    @Override
    public List<DataParamTempVO> listByRuleDictIds(String type, List<String> ruleDictIds) {
        // 过滤掉随机数和顺序数
        List<Long> ruleDictIdList = ruleDictIds.stream()
                .filter(dict -> !(dict.startsWith("#") || dict.startsWith("%")))
                .map(Long::parseLong).collect(Collectors.toList());
        // 所有规则字典
        List<CodeRuleDictDO> codeRuleDictList = codeRuleDictDAO
                .selectList(Wrappers.<CodeRuleDictDO>lambdaQuery()
                        .in(CodeRuleDictDO::getId, ruleDictIdList));
        // 所有规则字典的规则id
        List<Long> ruleIdList = codeRuleDictList.stream()
                .map(CodeRuleDictDO::getRuleId)
                .distinct()
                .collect(Collectors.toList());
        // 所有数据
        if (CollUtil.isEmpty(ruleIdList)) {
            return CollUtil.newArrayList();
        }
        List<DataParamTempDO> dataParamTempDOS = dataParamTempDAO.selectList(Wrappers.<DataParamTempDO>lambdaQuery()
                .eq(DataParamTempDO::getRelationType, 1)
                .in(DataParamTempDO::getRelationId, ruleIdList));

        // 所有数据的详情
        return dataParamTempDOS.stream()
                .map(this::buildDataParamTempVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取设备参量列表 按设备模型 ID
     *
     * @param modelId 型号编号
     * @return {@link List}<{@link DataParamTempVO}>
     */
    @Override
    public List<DataParamTempVO> listByModelId(Long modelId) {
        List<DataParamTempDO> dataParamTempDOS = dataParamTempDAO.selectList(Wrappers.<DataParamTempDO>lambdaQuery()
                .eq(DataParamTempDO::getRelationType, 2)
                .eq(DataParamTempDO::getRelationId, modelId));
        return dataParamTempDOS.stream()
                .map(this::buildDataParamTempVO)
                .collect(Collectors.toList());
    }

    /**
     * 导入设备参量临时数据
     *
     * @param dataParamExcelList Data param Excel DTOS
     */
    @Override
    public void importDataParamBase(List<DataParamExcelVO> dataParamExcelList) {
        if (CollUtil.isEmpty(dataParamExcelList)) {
            return;
        }
        List<DataParamTempDO> toSaveList = BeanUtils.copyToList(dataParamExcelList, DataParamTempDO.class);
        List<DataParamTempDO> dataParamTempDOS = checkListName(toSaveList);
        if (CollUtil.isEmpty(dataParamTempDOS)) {
            return;
        }
        dataParamTempDAO.insertBatch(dataParamTempDOS);
    }

    /**
     * 导入设备参量临时数据 频率
     *
     * @param frequencyExcelDTOList Data param Excel DTOS
     */
    @Override
    public void importFrequencyExcel(List<FrequencyExcelDTO> frequencyExcelDTOList) {
        if (CollUtil.isEmpty(frequencyExcelDTOList)) {
            return;
        }
        Map<Long, FrequencyExcelDTO> updateMap = frequencyExcelDTOList.stream().collect(Collectors.toMap(FrequencyExcelDTO::getDataParamId, item -> item));
        List<DataParamTempDO> dataParamTempDOList = dataParamTempDAO.selectList(Wrappers.<DataParamTempDO>lambdaQuery()
                .in(DataParamTempDO::getId, updateMap.keySet()));
        if (CollUtil.isEmpty(dataParamTempDOList)) {
            return;
        }
        dataParamTempDOList.forEach(dataParamTempDO -> {
            FrequencyExcelDTO frequencyExcelDTO = updateMap.get(dataParamTempDO.getId());
            dataParamTempDO.setFrequency(frequencyExcelDTO.getFrequency());
            dataParamTempDO.setFrequencyUnit(frequencyExcelDTO.getFrequencyUnit());
            dataParamTempDO.setAlgorithmName(frequencyExcelDTO.getAlgorithmName());
            dataParamTempDAO.updateById(dataParamTempDO);
        });
    }


    /**
     * 导入设备参量临时数据 算法
     *
     * @param algorithmExcelVOList Data param Excel DTOS
     */
    @Override
    public void importAlgorithmExcel(List<AlgorithmExcelVO> algorithmExcelVOList) {
        if (CollUtil.isEmpty(algorithmExcelVOList)) {
            return;
        }

        List<TempAlgorithmRelationDO> toSaveList = BeanUtils.copyToList(algorithmExcelVOList, TempAlgorithmRelationDO.class);
        List<TempAlgorithmRelationDO> algorithmRelationList = checkListByDataParamId(toSaveList);
        if (CollUtil.isEmpty(algorithmRelationList)) {
            return;
        }
        algorithmTempDAO.insertBatch(algorithmRelationList);
    }

    /**
     * 导入设备参量临时数据 算法参数
     *
     * @param algorithmParamExcelVOList Data param Excel DTOS
     */
    @Override
    public void importAlgorithmParamExcel(List<AlgorithmParamExcelVO> algorithmParamExcelVOList) {
        if (CollUtil.isEmpty(algorithmParamExcelVOList)) {
            return;
        }
        List<TempParamRelationDO> toSaveList = BeanUtils.copyToList(algorithmParamExcelVOList, TempParamRelationDO.class);
        cleanAlgorithmParamByDataParamId(toSaveList);
        paramTempDAO.insertBatch(toSaveList);
    }

    @Override
    public void importLabelExcel(List<LabelVO> labelVOList) {
        if (CollUtil.isEmpty(labelVOList)) {
            return;
        }
        List<LabelTempDO> toSaveList = BeanUtils.copyToList(labelVOList, LabelTempDO.class);
        cleanLabelByDataParamId(toSaveList);
        labelTempDAO.insertBatch(toSaveList);
    }

    /**
     * 导入告警 Excel
     *
     * @param alarmExcelVOList alarm Excel volist
     */
    @Override
    public void importAlarmExcel(List<AlarmVO> alarmExcelVOList) {
        if (CollUtil.isEmpty(alarmExcelVOList)) {
            return;
        }
        List<AlarmTempDO> toSaveList = BeanUtils.copyToList(alarmExcelVOList, AlarmTempDO.class);
        cleanAlarmByDataParamId(toSaveList);
        alarmTempDAO.insertBatch(toSaveList);
    }

    private void cleanAlarmByDataParamId(List<AlarmTempDO> toSaveList) {
        alarmTempDAO.delete(Wrappers.<AlarmTempDO>lambdaQuery()
                .in(AlarmTempDO::getDataParamId, toSaveList.stream()
                        .map(AlarmTempDO::getDataParamId).collect(Collectors.toList())));
    }

    private void cleanLabelByDataParamId(List<LabelTempDO> toSaveList) {
        labelTempDAO.delete(Wrappers.<LabelTempDO>lambdaQuery()
                .in(LabelTempDO::getDataParamId, toSaveList.stream()
                        .map(LabelTempDO::getDataParamId).collect(Collectors.toList())));
    }

    private void cleanAlgorithmParamByDataParamId(List<TempParamRelationDO> toSaveList) {
        algorithmTempDAO.delete(Wrappers.<TempAlgorithmRelationDO>lambdaQuery()
                .in(TempAlgorithmRelationDO::getDataParamId, toSaveList.stream()
                        .map(TempParamRelationDO::getDataParamId).collect(Collectors.toList())));
    }


    private List<TempAlgorithmRelationDO> checkListByDataParamId(List<TempAlgorithmRelationDO> toSaveList) {
        Map<Long, TempAlgorithmRelationDO> mapName = toSaveList.stream().collect(Collectors.toMap(TempAlgorithmRelationDO::getDataParamId, item -> item));
        // 获取所有的设备模型名称
        Set<Long> dataParamIds = mapName.keySet();
        List<TempAlgorithmRelationDO> list = algorithmTempDAO.selectList(Wrappers.<TempAlgorithmRelationDO>lambdaQuery()
                .in(TempAlgorithmRelationDO::getDataParamId, dataParamIds));
        // 如果数据库中没有重复的，直接返回
        if (CollUtil.isEmpty(list)) {
            return toSaveList;
        }
        // 去除已存在的
        list.stream().map(TempAlgorithmRelationDO::getDataParamId).forEach(mapName::remove);
        return new ArrayList<>(mapName.values());
    }

    private List<DataParamTempDO> checkListName(List<DataParamTempDO> toSaveList) {
        Map<String, DataParamTempDO> mapName = toSaveList.stream().collect(Collectors.toMap(DataParamTempDO::getName, item -> item));
        // 获取所有的设备模型名称
        Set<String> strings = mapName.keySet();
        List<DataParamTempDO> list = dataParamTempDAO.selectList(Wrappers.<DataParamTempDO>lambdaQuery()
                .in(DataParamTempDO::getName, strings));
        // 如果数据库中没有重复的，直接返回
        if (CollUtil.isEmpty(list)) {
            return toSaveList;
        }
        // 去除已存在的
        list.stream().map(DataParamTempDO::getName).forEach(mapName::remove);
        return new ArrayList<>(mapName.values());
    }


    /**
     * 构建数据参数临时 DTO
     *
     * @param paramTempDO 参数温度做
     * @return {@link DataParamTempVO}
     */
    private DataParamTempVO buildDataParamTempVO(DataParamTempDO paramTempDO) {
        DataParamTempVO dataParamTempVO = BeanUtils.copyToObject(paramTempDO, DataParamTempVO.class);
        Long id = paramTempDO.getId();
        Integer source = paramTempDO.getSource();
        // 设置算法及参数
        if (source != null && source == 2) {
            TempAlgorithmRelationDO algorithmRelation = algorithmTempDAO
                    .selectOne(new LambdaQueryWrapper<TempAlgorithmRelationDO>()
                            .eq(TempAlgorithmRelationDO::getDataParamId, id)
                            .last("limit 1"));
            AlgorithmVO algorithmVO = BeanUtils.copyToObject(algorithmRelation, AlgorithmVO.class);
            // 设置参数
            if (algorithmVO != null) {
                List<TempParamRelationDO> tempParamRelationList = paramTempDAO.selectList(new LambdaQueryWrapper<TempParamRelationDO>()
                        .eq(TempParamRelationDO::getDataParamId, id));
                List<ParamTempVO> paramTempList = BeanUtils.copyToList(tempParamRelationList, ParamTempVO.class);
//                algorithmVO.setParamTempList(paramTempList);
                algorithmVO.setConfigParamList(paramTempList);
            }
            dataParamTempVO.setAlgorithm(algorithmVO);
        }
        // 设置报警
        List<AlarmTempDO> alarmTempList = alarmTempDAO.selectList(new LambdaQueryWrapper<AlarmTempDO>()
                .eq(AlarmTempDO::getDataParamId, id));
        dataParamTempVO.setAlarmList(BeanUtils.copyToList(alarmTempList, AlarmVO.class));
        // 设置标签
        List<LabelTempDO> labelTempList = labelTempDAO.selectList(new LambdaQueryWrapper<LabelTempDO>()
                .eq(LabelTempDO::getDataParamId, id));
        dataParamTempVO.setLabelList(BeanUtils.copyToList(labelTempList, LabelVO.class));
        return dataParamTempVO;
    }

    /**
     * 清除所有id
     *
     * @param dataParamTempVO 设备参量临时数据
     */
    private void cleanAllId(DataParamTempVO dataParamTempVO) {
        // 系统计算
        if (dataParamTempVO.getSource() != null && dataParamTempVO.getSource() == 2) {
            Optional.ofNullable(dataParamTempVO.getAlgorithm())
                    .ifPresent(algorithmTempVO -> algorithmTempVO.setId(null));

            if (ObjectUtil.isNotEmpty(dataParamTempVO.getAlgorithm())) {
                Optional.ofNullable(dataParamTempVO.getAlgorithm().getConfigParamList())
                        .ifPresent(configParamTempList -> configParamTempList
                                .forEach(paramTemp -> paramTemp.setId(null)));
            }
        }

        Optional.ofNullable(dataParamTempVO.getAlarmList())
                .ifPresent(configAlarmTempVOS -> configAlarmTempVOS
                        .forEach(alarmTempVO -> alarmTempVO.setId(null)));
        Optional.ofNullable(dataParamTempVO.getLabelList())
                .ifPresent(configLabelTempVOS -> configLabelTempVOS
                        .forEach(labelTempVO -> labelTempVO.setId(null)));
    }


    /**
     * 标签列表
     *
     * @param configLabelList 标签列表
     * @param dataParamTempId 设备参量id
     */
    private void toSaveLabelList(List<LabelVO> configLabelList, Long dataParamTempId) {
        labelTempDAO.delete(new LambdaQueryWrapper<LabelTempDO>().eq(LabelTempDO::getDataParamId, dataParamTempId));
        if (CollUtil.isEmpty(configLabelList)) {
            return;
        }
        List<LabelTempDO> toSaveList = configLabelList.stream().map(labelTempDTO -> {
            LabelTempDO labelTempDO = BeanUtils.copyToObject(labelTempDTO, LabelTempDO.class);
            labelTempDO.setDataParamId(dataParamTempId);
            return labelTempDO;
        }).collect(Collectors.toList());
        labelTempDAO.insertBatch(toSaveList);
    }

    /**
     * 报警列表
     *
     * @param configAlarmList 报警列表
     * @param dataParamTempId 设备参量id
     */
    private void toSaveAlarmList(List<AlarmVO> configAlarmList, Long dataParamTempId) {
        alarmTempDAO.delete(new LambdaQueryWrapper<AlarmTempDO>().eq(AlarmTempDO::getDataParamId, dataParamTempId));
        if (CollUtil.isEmpty(configAlarmList)) {
            return;
        }
        List<AlarmTempDO> toSaveList = configAlarmList.stream().map(alarmTempDTO -> {
            AlarmTempDO alarmTempDO = BeanUtils.copyToObject(alarmTempDTO, AlarmTempDO.class);
            alarmTempDO.setDataParamId(dataParamTempId);
            return alarmTempDO;
        }).collect(Collectors.toList());
        alarmTempDAO.insertBatch(toSaveList);
    }

    /**
     * 算法公式对象
     *
     * @param configAlgorithm 配置算法
     * @param dataParamTempId 设备参量id
     */
    private void toSaveAlgorithm(AlgorithmVO configAlgorithm, Long dataParamTempId) {
        algorithmTempDAO.delete(new LambdaQueryWrapper<TempAlgorithmRelationDO>().eq(TempAlgorithmRelationDO::getDataParamId, dataParamTempId));
        if (ObjectUtil.isNull(configAlgorithm)) {
            toSaveParamList(null, dataParamTempId);
            return;
        }
        TempAlgorithmRelationDO tempAlgorithmRelationDO = BeanUtils.copyToObject(configAlgorithm, TempAlgorithmRelationDO.class);
        tempAlgorithmRelationDO.setDataParamId(dataParamTempId);
        boolean result = SqlHelper.retBool(algorithmTempDAO.insert(tempAlgorithmRelationDO));
        if (result) {
            // 保存 参数列表
            toSaveParamList(configAlgorithm.getConfigParamList(), dataParamTempId);
        }
    }


    /**
     * 保存参数列表
     *
     * @param configParamList 参数列表
     * @param dataParamTempId 设备参量id
     */
    private void toSaveParamList(List<ParamTempVO> configParamList, Long dataParamTempId) {
        paramTempDAO.delete(new LambdaQueryWrapper<TempParamRelationDO>().eq(TempParamRelationDO::getDataParamId, dataParamTempId));

        if (CollUtil.isEmpty(configParamList)) {
            return;
        }
        List<TempParamRelationDO> toSaveList = configParamList.stream().map(paramTempDTO -> {
            TempParamRelationDO tempParamRelationDO = BeanUtils.copyToObject(paramTempDTO, TempParamRelationDO.class);
            tempParamRelationDO.setDataParamId(dataParamTempId);
            return tempParamRelationDO;
        }).collect(Collectors.toList());
        paramTempDAO.insertBatch(toSaveList);
    }

}